<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
import React, { useState, useEffect } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { Button, Row, Col, FormText } from 'reactstrap';
import { Translate, translate, ValidatedField, ValidatedForm, isEmail } from 'react-jhipster';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowLeft, faSave } from '@fortawesome/free-solid-svg-icons';

<%_ if (enableTranslation) { _%>
import { locales, languages } from 'app/config/translation';
<%_ } _%>
import { getUser, getRoles, updateUser, createUser, reset } from './user-management.reducer';
import { useAppDispatch, useAppSelector } from 'app/config/store';

export const UserManagementUpdate = () => {
  const dispatch = useAppDispatch();

  const navigate = useNavigate();

  const { login } = useParams<'login'>();
  const isNew = login === undefined;

  useEffect(() => {
    if (isNew) {
      dispatch(reset());
    } else {
      dispatch(getUser(login));
    }
    dispatch(getRoles());
    return () => {
      dispatch(reset());
    };
  }, [login]);

  const handleClose = () => {
    navigate('/admin/user-management');
  };

  const saveUser = values => {
    if (isNew) {
      dispatch(createUser(values));
    } else {
      dispatch(updateUser(values));
    }
    handleClose();
  };

  const user = useAppSelector(state => state.userManagement.user);
  const loading = useAppSelector(state => state.userManagement.loading);
  const updating = useAppSelector(state => state.userManagement.updating);
  const authorities = useAppSelector(state => state.userManagement.authorities);

  return (
    <div>
      <Row className="justify-content-center">
        <Col md="8">
          <h1>
            <Translate contentKey="userManagement.home.createOrEditLabel">Create or edit a User</Translate>
          </h1>
        </Col>
      </Row>
      <Row className="justify-content-center">
        <Col md="8">
        { loading ? <p>Loading...</p>
        : <ValidatedForm onSubmit={saveUser} defaultValues={user}>
          {user.id && (
            <ValidatedField
              type="text"
              name="id"
              required
              readOnly
              label={translate('global.field.id')}
              validate={{ required: true }}
            />
          )}
          <ValidatedField
            type="text"
            name="login"
            label={translate('userManagement.login')}
            validate={{
              required: {
                value: true,
                message: translate('register.messages.validate.login.required'),
              },
              pattern: {
                value: /<%- webappLoginRegExp %>/,
                message: translate('register.messages.validate.login.pattern'),
              },
              minLength: {
                value: 1,
                message: translate('register.messages.validate.login.minlength'),
              },
              maxLength: {
                value: 50,
                message: translate('register.messages.validate.login.maxlength'),
              },
            }}
          />
          <ValidatedField
            type="text"
            name="firstName"
            label={translate('userManagement.firstName')}
            validate={{
              maxLength: {
                value: 50,
                message: translate('entity.validation.maxlength', { max: 50 }),
              },
            }}
          />
          <ValidatedField
            type="text"
            name="lastName"
            label={translate('userManagement.lastName')}
            validate={{
              maxLength: {
                value: 50,
                message: translate('entity.validation.maxlength', { max: 50 }),
              },
            }}
          />
          <FormText>This field cannot be longer than 50 characters.</FormText>
          <ValidatedField
            name="email"
            label={translate('global.form.email.label')}
            placeholder={translate('global.form.email.placeholder')}
            type="email"
            validate={{
              required: {
                value: true,
                message: translate('global.messages.validate.email.required'),
              },
              minLength: {
                value: 5,
                message: translate('global.messages.validate.email.minlength'),
              },
              maxLength: {
                value: 254,
                message: translate('global.messages.validate.email.maxlength'),
              },
              validate: v => isEmail(v) || translate('global.messages.validate.email.invalid'),
            }}
          />
          <ValidatedField
            type="checkbox"
            name="activated"
            check
            value={true}
            disabled={!user.id}
            label={translate('userManagement.activated')}
          />
<%_ if (enableTranslation) { _%>
          <ValidatedField type="select" name="langKey" label={translate('userManagement.langKey')}>
            {locales.map(locale => (
              <option value={locale} key={locale}>
                {languages[locale].name}
              </option>
            ))}
          </ValidatedField>
<%_ } _%>
          <ValidatedField type="select" name="authorities" multiple label={translate('userManagement.profiles')}>
            {authorities.map(role => (
              <option value={role} key={role}>
                {role}
              </option>
            ))}
          </ValidatedField>
          <Button tag={Link} to="/admin/user-management" replace color="info">
            <FontAwesomeIcon icon={faArrowLeft} />&nbsp;
            <span className="d-none d-md-inline">
              <Translate contentKey="entity.action.back">Back</Translate>
            </span>
          </Button>
          &nbsp;
          <Button color="primary" type="submit" disabled={updating}>
            <FontAwesomeIcon icon={faSave} />&nbsp;
            <Translate contentKey="entity.action.save">Save</Translate>
          </Button>
        </ValidatedForm>
        }
        </Col>
      </Row>
    </div>
  );
};

export default UserManagementUpdate;
